package com.app.reportproblem;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.json.JSONException;
import org.json.JSONObject;

import com.app.reportproblem.MyUI.KeyboardHelper;
import com.app.reportproblem.Utils.PreferenceHelper;
import com.app.reportproblem.httpclient.HttpClientHelper;
import com.app.reportproblem.httpclient.MyJsonHttpResponseHandler;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.model.GraphUser;
import com.td.auth.googleplus.SignInGoogleActivity;

import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener, OnTouchListener{
	
	ImageButton btnLoginWithFacebook, btnSignIn, btnRegister;
	EditText edtEmail, edtPass;
	TextView txtForgotPass;
	View main;
	ImageButton btnLoginWithGoogle;
	ProgressDialog progressDialog;
	PreferenceHelper preferenceHelper;
	
	Dialog dF;
	EditText edtForgot;
	
	// login facebook
	 // Your Facebook APP ID
    private static String APP_ID = "496033847186087"; // Replace your App ID here
 // Instance of Facebook Class
    private Facebook facebook;
    private AsyncFacebookRunner mAsyncRunner;
    String FILENAME = "AndroidSSO_data";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		main = (View) findViewById(R.id.main_login);
		KeyboardHelper.setupUI(LoginActivity.this, main);
		
		preferenceHelper = new PreferenceHelper(this);
		
		facebook = new Facebook(APP_ID);
        mAsyncRunner = new AsyncFacebookRunner(facebook);
		
		btnLoginWithGoogle = (ImageButton) findViewById(R.id.btn_login_google);
		btnLoginWithFacebook = (ImageButton) findViewById(R.id.btn_login_facebook);
		btnSignIn = (ImageButton) findViewById(R.id.btn_sign_in);
		btnRegister = (ImageButton) findViewById(R.id.btn_resgiter);
		txtForgotPass = (TextView) findViewById(R.id.txt_forgot_pass);
		
		edtEmail = (EditText) findViewById(R.id.edt_email);
		edtPass = (EditText) findViewById(R.id.edt_pass);
		
		init();
		getKeyHash();
//		logoutFromFacebook();
	}
	
	void init() {
		btnLoginWithFacebook.setOnTouchListener(this);
		btnLoginWithGoogle.setOnTouchListener(this);
		btnSignIn.setOnTouchListener(this);
		btnRegister.setOnTouchListener(this);
		txtForgotPass.setOnClickListener(this);
		
		edtPass.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				KeyboardHelper.hideSoftKeyboard(LoginActivity.this);
				login();
				return false;
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_login_google:
			loginWithGoogle();
			break;
		case R.id.btn_login_facebook:
//			loginWithFacebook();
//			loginWithActivity();
			loginFB();
			break;
		case R.id.btn_sign_in:
			KeyboardHelper.hideSoftKeyboard(LoginActivity.this);
			validate();
			break;
		case R.id.btn_resgiter:
			gotoRegister();
			break;
		case R.id.txt_forgot_pass:
			showDialogForgot();
			break;
		default:
			break;
		}
	}
	
	void getKeyHash() {
		 try {
	            PackageInfo info = getPackageManager().getPackageInfo(
	                    "com.app.reportproblem", 
	                    PackageManager.GET_SIGNATURES);
	            for (Signature signature : info.signatures) {
	                MessageDigest md = MessageDigest.getInstance("SHA");
	                md.update(signature.toByteArray());
	                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
	                }
	        } catch (NameNotFoundException e) {

	        } catch (NoSuchAlgorithmException e) {

	        }
	}

	void gotoRegister() {
		Intent t = new Intent(LoginActivity.this, RegisterActivity.class);
		startActivity(t);
		overridePendingTransition(R.anim.open_next, R.anim.close_main);
	}
	
	void gotoFacebook() {
		Intent t = new Intent(LoginActivity.this, LoginFBActivity.class);
		startActivity(t);
		overridePendingTransition(R.anim.open_next, R.anim.close_main);
	}
	
	void validate(){
		if (!edtEmail.getText().toString().matches("")){
			if (!edtPass.getText().toString().matches("")) {
				login();
			} else {
				Toast.makeText(LoginActivity.this, getString(R.string.passrong), Toast.LENGTH_SHORT).show();
			}
			
		} else {
			Toast.makeText(LoginActivity.this, getString(R.string.emailrong), Toast.LENGTH_SHORT).show();
		}
	}
	
	void loginWithActivity() {
		Intent t = new Intent(LoginActivity.this, LoginFBActivity.class);
		startActivity(t);
	}
	void login() {
		
		progressDialog = ProgressDialog.show(LoginActivity.this, "", getString(R.string.logging));
		
		
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				progressDialog.dismiss();
				super.onFailure(error);
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					progressDialog.dismiss();
					int status = re.getInt("status");
					switch (status) {
					case 200:
						gotoMain();
						JSONObject data = re.getJSONObject("data");
						Log.i("DATA", "USERID"+data.toString());
						preferenceHelper.setUserId(data.getInt("userId"));
						preferenceHelper.setName(data.getString("name"));
						preferenceHelper.setMobile(data.getString("mobile"));
						preferenceHelper.setEmail(edtEmail.getText().toString());
						preferenceHelper.setPass(edtPass.getText().toString());
						preferenceHelper.setFixed(data.getInt("allowFix"));
						Log.i("DATA", ""+preferenceHelper.getUserId());
						break;
					case 400:
						Toast.makeText(LoginActivity.this, getString(R.string.invalid), Toast.LENGTH_SHORT).show();
						break;
					case 401:
						Toast.makeText(LoginActivity.this, getString(R.string.emailauthentication), Toast.LENGTH_SHORT).show();
						break;
					case 404:
						Toast.makeText(LoginActivity.this, getString(R.string.notfound), Toast.LENGTH_SHORT).show();
						break;

					default:
						break;
					}
				} catch (JSONException e) {
					Toast.makeText(LoginActivity.this, getString(R.string.notconnectserver), Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}
			}
			
		});
		httpClientHelper.login(edtEmail.getText().toString(), edtPass.getText().toString());
	}
	
	void gotoMain() {
		finish();
		Intent t = new Intent(LoginActivity.this, MainActivity.class);
		t.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(t);
	}
	
	void forgotPass() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				Toast.makeText(LoginActivity.this, getString(R.string.notconnectserver), Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					int status = re.getInt("status");
					switch (status) {
					case 200:
						// hien thi thong bao da gui email o day
						Toast.makeText(LoginActivity.this, getString(R.string.sendForgotSuccess), Toast.LENGTH_SHORT).show();
						break;
					case 400:
						Toast.makeText(LoginActivity.this, getString(R.string.invalid), Toast.LENGTH_SHORT).show();
						break;
					case 404:
						Toast.makeText(LoginActivity.this, getString(R.string.notfound), Toast.LENGTH_SHORT).show();
						break;

					default:
						break;
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
			}
			
		});
		httpClientHelper.forgotPass(edtForgot.getText().toString());
	}
	
	
	
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	void loginFB(){
		
		progressDialog = ProgressDialog.show(LoginActivity.this, "", getString(R.string.logging));
		
		// start Facebook Login
        Session.openActiveSession(this, true, new Session.StatusCallback() {

            // callback when session changes state
            @Override
            public void call(final Session session, SessionState state,
                    Exception exception) {
                if (session.isOpened()) {

                    // make request to the /me API
                    Request.executeMeRequestAsync(session,
                            new Request.GraphUserCallback() {

                                // callback after Graph API response with user
                                // object
                                @Override
                                public void onCompleted(GraphUser user,
                                        Response response) {
                                    if (user != null) {
                                        Log.i("DATA", user.getName());
                                        Session session = Session.getActiveSession();
                                	    if (session.isOpened()) {
//                                	        Toast.makeText(LoginActivity.this, session.getAccessToken(), Toast.LENGTH_LONG).show();
                                	        preferenceHelper.setAccessToken(session.getAccessToken());
                                	        loginHttpFacebook();
                                	    }
                                    }
                                }

                            });
                }
            }

        });

    }
	
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
	            resultCode, data);
	}

	
	
	void loginWithGoogle() {
		Intent t = new Intent(LoginActivity.this, SignInGoogleActivity.class);
		startActivity(t);
	}
	
	void showDialogForgot() {
		dF = new Dialog(LoginActivity.this);
		dF.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dF.setContentView(R.layout.dialog_forgot);
		
		
		edtForgot = (EditText) dF.findViewById(R.id.edt_forgot);
		if (edtEmail.getText().toString().equals("")) {
			
		} else {
			edtForgot.setText(edtEmail.getText().toString());
		}
		edtForgot.setSelection(edtForgot.getText().length());
		Button btnOk = (Button) dF.findViewById(R.id.btnOk);
		btnOk.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dF.dismiss();
				forgotPass();
			}
		});
		dF.show();
	}
	
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	void loginHttpFacebook() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					int status = re.getInt("status");
					progressDialog.dismiss();
					switch (status) {
					case 200:
						JSONObject data = re.getJSONObject("data");
						preferenceHelper.setUserId(data.getInt("userId"));
						preferenceHelper.setName(data.getString("name"));
						preferenceHelper.setMobile(data.getString("mobile"));
						preferenceHelper.setEmail(edtEmail.getText().toString());
						preferenceHelper.setPass(edtPass.getText().toString());
						preferenceHelper.setFixed(data.getInt("allowFix"));
						Log.i("DATA", "Dang nhap thanh cong");
						gotoMain();
						break;

					default:
						break;
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		});
		
		httpClientHelper.loginSocial(preferenceHelper.getAccessToken(), "facebook");
		
	}
	
	@SuppressWarnings("deprecation")
	public void logoutFromFacebook() {
	    mAsyncRunner.logout(this, new RequestListener() {
	        @Override
	        public void onComplete(String response, Object state) {
	            Log.d("Logout from Facebook", response);
	            if (Boolean.parseBoolean(response) == true) {
	                // User successfully Logged out
	            }
	        }
	 
	        @Override
	        public void onIOException(IOException e, Object state) {
	        }
	 
	        @Override
	        public void onFileNotFoundException(FileNotFoundException e,
	                Object state) {
	        }
	 
	        @Override
	        public void onMalformedURLException(MalformedURLException e,
	                Object state) {
	        }

			@Override
			public void onFacebookError(FacebookError e, Object state) {
				// TODO Auto-generated method stub
				
			}
	 
	    });
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.btn_login_facebook:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				loginFB();
			}
			break;
		case R.id.btn_login_google:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				loginWithGoogle();
			}
			break;
		case R.id.btn_resgiter:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				gotoRegister();
			}
			break;
		case R.id.btn_sign_in:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				KeyboardHelper.hideSoftKeyboard(LoginActivity.this);
				validate();
			}
			break;
		default:
			break;
		}
		return false;
	}
}
